package serverc

import (
	"FastDevelopGo/src/base/mess"
	"github.com/gin-gonic/gin"
	"github.com/go-oauth2/oauth2/v4/errors"
	"github.com/go-oauth2/oauth2/v4/manage"
	"github.com/go-oauth2/oauth2/v4/models"
	"github.com/go-oauth2/oauth2/v4/server"
	"github.com/go-oauth2/oauth2/v4/store"
	oredis "github.com/go-oauth2/redis/v4"
	"github.com/go-redis/redis/v8"
	"log"
	"net/http"
)

var (
	SERVER *server.Server
)

// InitServer 启动OAuth2 Server
func InitServer() {
	// 生成默认管理
	manager := manage.NewDefaultManager()
	// token 存储位置,可使用redis或数据库
	manager.MapTokenStorage(oredis.NewRedisStore(&redis.Options{
		Addr: "127.0.0.1:6379",
		DB:   15,
	}))
	// 应用、账号存储
	clientStore := store.NewClientStore()
	// 添加一个测试账号
	clientStore.Set("000000", &models.Client{
		ID:     "000000",
		Secret: "999999",
		Domain: "http://127.0.0.1:8080",
	})
	manager.MapClientStorage(clientStore)

	SERVER = server.NewDefaultServer(manager)
	SERVER.SetAllowGetAccessRequest(true)
	SERVER.SetClientInfoHandler(server.ClientFormHandler)

	SERVER.SetInternalErrorHandler(func(err error) (re *errors.Response) {
		log.Println("Internal Error:", err.Error())
		return
	})

	SERVER.SetResponseErrorHandler(func(re *errors.Response) {
		log.Println("Response Error:", re.Error.Error())
	})

	http.HandleFunc("/authorize", func(w http.ResponseWriter, r *http.Request) {
		err := SERVER.HandleAuthorizeRequest(w, r)
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
		}
	})

	http.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) {
		SERVER.HandleTokenRequest(w, r)
	})

	log.Fatal(http.ListenAndServe(":9096", nil))
}

// Token 获取token
func Token(c *gin.Context) {
	err := SERVER.HandleTokenRequest(c.Writer, c.Request)
	if err != nil {
		c.JSON(http.StatusBadRequest, mess.ResErrMess("0x0100102", err.Error()))
		return
	}
}

// Authorize 授权验证
func Authorize(c *gin.Context) {
	err := SERVER.HandleAuthorizeRequest(c.Writer, c.Request)
	if err != nil {
		c.JSON(http.StatusBadRequest, mess.ResErrMess("0x0100101", err.Error()))
		return
	}
}
